<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="询价单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billcode">
              <a-input v-model="model.billcode" disabled="true"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="城市/地区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cityid">
              <j-area-linkage type="cascader" v-model="model.cityid" placeholder="请输入省市区" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="地区" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="regionid">
              <j-area-linkage type="cascader" v-model="model.regionid" placeholder="请输入省市区" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="6">
            <a-form-model-item label="车辆信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="vehicle">
              <a-input v-model="model.vehicle" placeholder="请输入车辆信息"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="车牌号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="plate">
              <a-input v-model="model.plate" placeholder="请输入车牌号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="车架号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="vin">
              <a-input v-model="model.vin" placeholder="请输入车架号"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="事故号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="accidentNumber">
              <a-input v-model="model.accidentNumber" placeholder="请输入事故号"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="6">
            <a-form-model-item label="配件数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="partcount">
              <a-input-number disabled="true" v-model="model.partcount" placeholder="请输入配件数量" style="width: 100%" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="6">
            <a-form-model-item label="报案号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bah">
              <a-input v-model="model.bah" placeholder="请输入报案号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="修理厂地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xlcaddress">
              <a-input v-model="model.xlcaddress" placeholder="请输入修理厂地址"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="修理厂联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xlclink">
              <a-input v-model="model.xlclink" placeholder="请输入修理厂联系方式"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="6">
            <a-form-model-item label="单据状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
              <j-dict-select-tag placeholder="请输入单据状态" v-model="model.status" dictCode="djtype" :async="true"
                :disabled="true">
              </j-dict-select-tag>
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :span="6">
            <a-form-model-item label="审核状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="auditstatus">
              <j-dict-select-tag placeholder="请输入单据状态" v-model="model.auditstatus" dictCode="auditflag" :async="true"
                :disabled="true">
              </j-dict-select-tag>
            </a-form-model-item>
          </a-col> -->
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="事故图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="accidentimagesString">
              <j-image-upload isMultiple v-model="model.accidentimagesString" :bizPath="imgsrc"></j-image-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="行驶证图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="licenseimageString">
              <j-image-upload v-model="model.licenseimageString" @beforeUpload="handleOcr"></j-image-upload>
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- <a-col :span="6">
            <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createBy">
              <a-input v-model="model.createBy" placeholder="请输入创建人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date placeholder="请选择创建日期" v-model="model.createTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%" />
            </a-form-model-item>
          </a-col> -->

        <a-row>
          <a-col :span="12" v-show="this.canshow">
            <a-form-model-item label="地区驳回意见" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="regionrejectreason">
              <a-textarea type="textarea" v-model="model.regionrejectreason" :rows="2" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-show="this.canshow">
            <a-form-model-item label="省公司驳回意见" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provicerejectreason">
              <a-textarea type="textarea" v-model="model.provicerejectreason" :rows="2" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="询价单分录" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table keep-source :ref="refKeys[0]" :loading="scmxjditemTable.loading" :columns="scmxjditemTable.columns"
          :dataSource="scmxjditemTable.dataSource" :maxHeight="300" :disabled="formDisabled" :rowNumber="true"
          :alwaysEdit="true" :rowSelection="true" :toolbar="true">
          <template slot="toolbarSuffix" :disabled="formDisabled">
            <a-button type="export" @click="exportDataEvent" :disabled="formDisabled">导出模板</a-button>
            <a-button @click="adjustqtyclick" :disabled="formDisabled">批量调整配件数量</a-button>
            <a-button @click="adjustpzclick" :disabled="formDisabled">批量调整配件品质</a-button>
            <a-upload :file-list="fileList" :customRequest="importDataEvent">
              <a-button :disabled="formDisabled"> <a-icon type="upload" /> 选择导入文件 </a-button>
            </a-upload>
          </template>
        </j-vxe-table>
        <a-modal v-model="adjustqtyvisable" title="请输入配件数量" ok-text="确认" cancel-text="取消" @ok="adjustqtyres"
          @cancel="cancleqtyadjust">
          <!-- <a-textarea type="textarea" v-model="pjqty" :rows="4" /> -->
          <a-inputNumber v-model="pjqty"></a-inputNumber>
        </a-modal>

        <a-modal v-model="pjpzadjustvisable" title="请选择配件品质" ok-text="确认" cancel-text="取消" @ok="adjustpzres"
          @cancel="cancleqtyadjust">
          <a-form>
            <a-form-item label="配件品质多选" style="width: 300px">
              <j-multi-select-tag :width='200' v-model="selectpz" dictCode="pjpz" placeholder="请选择配件品质">
              </j-multi-select-tag>
            </a-form-item>
          </a-form>

        </a-modal>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { getAction, getFileAccessHttpUrl } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import Area from '@/components/_util/Area'
import * as XLSX from 'xlsx'
import { readFile } from '@/api/erp/commonapi'
import qs from 'qs'
import { postAction, postActionByOcr } from '../../../../../api/manage'

export default {
  name: 'ScmxjdForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {},
      pjqty: 0,
      selectpz: '',
      pjpzadjustvisable: false,
      adjustqtyvisable: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        cityid: [{ required: true, message: '请选择地区!' }],
        vehicle: [{ required: true, message: "请选择车辆信息" }],
        vin: [{ required: true, message: "请选择车架号" }],
        plate: [{ required: true, message: '请选择车牌号' }],
        accidentNumber: [{ required: true, message: '请选择事故号' }]
      },
      filelist: [],
      canshow: true,
      refKeys: ['scmxjditem'],
      tableKeys: ['scmxjditem'],
      activeKey: 'scmxjditem',
      // 询价单分录
      scmxjditemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '配件编码',
            key: 'matcode',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          },
          {
            title: '配件名称',
            key: 'matname',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '配件数量',
            key: 'count',
            type: JVXETypes.inputNumber,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '配件品质',
            key: 'quality',
            type: JVXETypes.list_multi,
            dictCode: 'pjpz',
            width: '400px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '备注',
            key: 'remarks',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: ''
          }
        ]
      },
      workbook: null,
      sheetNames: [],
      selectedSheet: '',
      sheetData: [],
      url: {
        add: '/rfq.xbj/scmxjd/add',
        edit: '/rfq.xbj/scmxjd/edit',
        queryById: '/rfq.xbj/scmxjd/queryById',
        scmxjditem: {
          list: '/rfq.xbj/scmxjd/queryScmxjditemByMainId'
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled () {
      return this.disabled
    }
  },
  created () {
    this.pcaData = new Area()
    if (this.model.id) {
    } else {
      this.model.auditstatus = '0'
      let currentuser = this.$store.getters.userInfo
      this.model.cityid = currentuser.regionid
    }
  },
  methods: {
    async adjustpzres () {
      console.log(this.selectpz);
      if (this.selectpz) {
        // let { xTable } = this.$refs.vxe.$refs;
        let tableData = this.$refs.scmxjditem.$refs.vxe.getTableData().fullData
        for (let i = 0; i < tableData.length; i++) {
          tableData[i].quality = this.selectpz;
        }

        await this.$refs.scmxjditem.$refs.vxe.updateData();
        this.pjpzadjustvisable = false;
      }
    },
    adjustpzclick () {
      this.pjpzadjustvisable = true;
    },
    async adjustqtyres () {
      console.log(this.pjqty);
      if (this.pjqty) {
        // let { xTable } = this.$refs.vxe.$refs;
        let tableData = this.$refs.scmxjditem.$refs.vxe.getTableData().fullData
        for (let i = 0; i < tableData.length; i++) {
          tableData[i].count = this.pjqty;
        }

        await this.$refs.scmxjditem.$refs.vxe.updateData();
        this.adjustqtyvisable = false;
      }
    },
    adjustqtyclick () {
      this.adjustqtyvisable = true;
    },
    cancleqtyadjust () {
      this.adjustqtyvisable = false;
    },
    getimgInfo (file) {
      return new Promise(resolve => {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = ev => {
          resolve(ev.target.result)
        }
      })
    },
    async handleOcr (file) {
      let imgdata = await this.getimgInfo(file);
      postAction("/rfq.xbj/scmxjd/getxzsinfo", { img: imgdata }).then(res => {
        if (res) {
          if (res.result) {
            let resu = res.result;
            console.log(resu);
            if (resu.error_msg == '') {
              let vehinfo = resu.front_result;
              this.model.vehicle = vehinfo.car_model;
              this.model.vin = vehinfo.vin_code;
              this.model.plate = vehinfo.car_no;
            }
          }
        }
      })
      return true;
    },
    exportDataEvent () {
      const data = [
        ['配件编码', '配件名称', '配件数量', '配件品质', '备注'],
        ['0001', '配件demo', 1, '原厂', ''],
      ];

      const ws = XLSX.utils.aoa_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
      XLSX.writeFile(wb, 'data.xlsx');
    },
    async importDataEvent (event) {
      // 读取文件
      let dataBinary = await readFile(event.file)
      let workBook = XLSX.read(dataBinary, { type: 'binary', cellDates: true })
      let workSheet = workBook.Sheets[workBook.SheetNames[0]]
      const data = XLSX.utils.sheet_to_json(workSheet)
      //备件编码、备件名称、备件数量、备件品质、备注
      for (let i = 0; i < data.length; i++) {
        let curObject = data[i]
        let newRow = {
          matcode: curObject.配件编码,
          matname: curObject.配件名称,
          count: curObject.配件数量,
          quality: curObject.配件品质,
          remarks: curObject.备注
        }
        this.scmxjditemTable.dataSource.push(newRow)
      }
      console.log(data) //这里已经能拿到转换后的json
    },
    beforeImportMethod (options) {
      console.log(options)
    },
    addBefore () {
      this.scmxjditemTable.dataSource = []
    },
    getAllTable () {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter () {
      this.$nextTick(() => { })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.scmxjditem.list, params, this.scmxjditemTable)
      } else {
        this.canshow = false
      }
    },
    //校验所有一对一子表表单
    validateSubForm (allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch(e => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData (allValues) {
      this.model = Object.assign(this.model, { fullcityname: this.pcaData.getText(this.model.cityid) })
      let formData = new FormData()
      formData.img = this.filelist
      this.model = Object.assign(this.model, { formdata: formData })
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        scmxjditemList: allValues.tablesValue[0].tableData
      }
    },
    validateError (msg) {
      this.$message.error(msg)
    }
  }
}
</script>

<style scoped></style>
